﻿using HBase;
using HBase.db;
using hCommand;
using Net.http;
using Persistence;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;

namespace Persistence {
    public class LocEngine : GkTransaction
    {
        public long id;
        public int ActiveStatus;
        public long areaId ;

        protected override TransRes Execute()
        {
            /*
            int working = queryUnique<int>("select count(*) from core_task where src=@id || des=@id", new { id });
            if (working > 0) {
                return new TransRes("有任务执行中不能修改库位状态");
            }

            */
            string sql = "update Core_Wh_Loc set area_Id= @areaId,  Active_Status = @activeStatus where id=@id ";
            if (ActiveStatus == 2 || ActiveStatus == 3) {
                String sql2 = "update Core_Stock set  status =@status where loc_id = @id";
                exec(sql2, new { id, status = (int)StockStatus.库位锁定 });
            } else if(ActiveStatus == 0 || ActiveStatus == 1) {
                String sql2 = "update Core_Stock set  status =@status where loc_id = @id  and status=@oldStatus";
                exec(sql2, new { id, status = (int)StockStatus.空闲 , oldStatus =(int)StockStatus.库位锁定 });
            }
            var old = getById<CoreWhLoc>(id);
            bool res = exec(sql, new { areaId , activeStatus = ActiveStatus , id }) == 1;

            if (old.areaId != areaId) {
                String s = " select  ca.priority from    core_wh_area ca join core_wh_loc l on l.area_Id = ca.id where l.id = @loc  ";
                int areaOrder = this.queryUnique<int>(s, new { loc = id });
                String s2 = " select  id  from    Core_Stock    where loc_Id=@locId  ";
                var ids = query<CoreStock>(s2, new { locId =id }).Select(p => p.id).ToList();
                if (ids.Count > 0) {
                    String sql2 = "update Core_Stock set  area_order =@areaOrder where id in @ids";
                    exec(sql2, new { ids, areaOrder });
                }

            }

            return new TransRes();
        }


       
    }
}
